package uk.co.q3c.deplan.client.domain.resource;

import javax.persistence.Transient;

import uk.co.q3c.deplan.client.domain.DomainKind;
import uk.co.q3c.deplan.client.domain.DomainObject;
import uk.co.q3c.deplan.client.domain.util.CalendarAdjustments;
import uk.co.q3c.deplan.client.service.ServiceFactory;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Serialized;
import com.googlecode.objectify.annotation.Unindexed;

/**
 * 
 * @author DSowerby 12 May 2008 22:46:51
 * 
 */
@Unindexed
@Cached(expirationSeconds = 600)
public class BaseCalendar extends WorkingCalendar {

	private static final long serialVersionUID = 1L;
	@Serialized
	private CalendarAdjustments adjustments;

	protected BaseCalendar() {
		super();

	}

	public BaseCalendar(ServiceFactory connection) {
		super(connection);

	}

	/**
	 * 
	 */
	@Override
	protected void beforeLoad() {
		super.beforeLoad();
		if (getBaseWorkingTime() == null) {
			createBaseWorkingTime();
		}
	}

	@Override
	public String toString() {
		return "Base Calendar";
	}

	@Transient
	private WorkingTime baseWorkingTime;

	/**
	 * Add an adjustment to working time for a given day. For a resource this is applied after any adjustments made at the base level (which
	 * apply to all resources). Note that there is no <code>removeAdjustment</code>, just call this with <code>absolute==true</code> and
	 * <code>minutes==0</code>
	 * 
	 * @param date
	 *            the date affected. Time is ignored. String must be a valid date for use with DateFormat
	 * 
	 * @param absolute
	 *            if true adjustment is absolute, else it is relative to the baseCalendar
	 * 
	 * @param minutes
	 *            number of minutes by which to adjust (positive or negative)
	 */

	@Override
	public WorkingTime getBaseWorkingTime() {
		if (baseWorkingTime == null) {
			createBaseWorkingTime();
		}
		return baseWorkingTime;
	}

	/**
	 * @see uk.co.q3c.deplan.client.domain.resource.WorkingCalendar#createAdjustments()
	 */
	@Override
	protected void createAdjustments() {
		adjustments = new CalendarAdjustments(getConnection());

	}

	/**
	 * Creates an instance of {@link DefaultWorkingTime} to use as the base working time
	 */
	protected void createBaseWorkingTime() {
		baseWorkingTime = new DefaultWorkingTime();

	}

	/**
	 * @see uk.co.q3c.deplan.client.domain.resource.WorkingCalendar#getAdjustments()
	 */
	@Override
	public CalendarAdjustments getAdjustments() {
		return adjustments;
	}

	@Override
	public DomainKind getKind() {
		return DomainKind.BaseCalendar;
	}

	@Override
	public Key<? extends DomainObject> getKey() throws PersistenceReferenceException {
		throw new RuntimeException("Not yet implemented");
	}

	@Override
	public void setKeyId(Long keyId) {
		throw new RuntimeException("Not yet implemented");
	}
}
